package com.ruoyi.plus.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.plus.utils.RsaUtils;
import com.ruoyi.plus.utils.sms.ISmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginPlusController {

    @Autowired
    private ISmsService smsService;


    /**
     * 获取公钥 前端用来密码加密
     *
     * @return
     */
    @GetMapping("/publicKey")
    public RsaUtils.RsaKeyPair publicKey() {
        RsaUtils.RsaKeyPair rsaKeyPair = new RsaUtils.RsaKeyPair();
        rsaKeyPair.setPublicKey(RsaUtils.getPublicKey());
        return rsaKeyPair;
    }

    /**
     * 登录获取手机号
     *
     * @return 结果
     */
    @GetMapping("/getPhone")
    public AjaxResult getPhone() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("phone", user.getPhonenumber());
        return ajax;
    }

    /**
     * 发送验证码未登录
     *
     * @return
     */
    @GetMapping("/sendSmsByPhone/{phoneNumber}")
    public AjaxResult sendSmsByPhone(@PathVariable String phoneNumber) {
        String code = smsService.genCode(phoneNumber);
        smsService.sendCode(phoneNumber, code);
        return AjaxResult.success("验证码发送成功！");
    }

    /**
     * 发送验证码
     *
     * @return
     */
    @GetMapping("/sendSms/{phoneNumber}")
    public AjaxResult sendSms(@PathVariable String phoneNumber) {
        String code = smsService.genCode(phoneNumber);
        smsService.sendCode(phoneNumber, code);
        return AjaxResult.success("验证码发送成功！");
    }

    /**
     * 验证码正确与否
     *
     * @param phoneNumber
     * @param code
     * @return
     */
    @GetMapping("/checkSms/{phoneNumber}/{code}")
    @ResponseBody
    public AjaxResult checkSms(@PathVariable String phoneNumber, @PathVariable String code) {
        Boolean checkCode = smsService.checkCode(phoneNumber, code).isCheckResult();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("isOk", checkCode);
        return ajax;
    }
}
